
/*
 * @Description: 流程设计模型部署表
 * @Author: DHL
 * @Date: 2022-08-23 15:26:03
 * @LastEditors: DHL
 * @LastEditTime: 2022-09-07 16:10:41
 */

import { defineComponent, computed, reactive, ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { assign, cloneDeep } from 'lodash-es'
import { TwTableOptions } from '/@/types/table.d'
import { arraySerializeToStr } from '/@/utils/twUtils'
import { usePermission } from '/@/hooks/web/permission'
import {
  ActReModelModel,
  ActReModelPageParams
} from '/@/api/flow/model/actReModelModel'
import { apiActReModelBatchDeleteByIds, apiActReModelCopy, apiActReModelDeploy, apiActReModelSearch } from '/@/api/flow/actReModel'
import actReModelForm from './form.vue'
import flowCategoryTree from '../components/flowCategoryTree.vue'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import { stringUtils } from '/@/utils/stringUtils'
import { router } from '/@/router'

export default defineComponent({
  name: 'ActReModel',
  components: { actReModelForm, flowCategoryTree, Splitpanes, Pane },
  setup(props) {
    //////////////////////////////////////////////////
    // 属性
    //////////////////////////////////////////////////

    const loading = ref(false)
    const loadingByDel = ref(false)

    // 权限控制
    const { hasPermission } = usePermission()

    /**
     * 表格数据
     */
    const tableData = ref()

    /**
     * 查询表单
     */
    const searchFormRef = ref()

    /**
     * 数据列表
     */
    const tableRef = ref()

    /**
     * 表单
     */
    const formRef = ref()

    /**
     * 公共
     */
    const state = reactive({})

    /**
     * 是否有选中的行
     */
    const isSelectRows = computed(() => {
      let selectRows: Array<ActReModelModel> = []
      if (tableRef.value) {
        selectRows = tableRef.value.getSelectRows()
      }
      return selectRows.length < 1
    })

    //////////////////////////////////////////////////
    // 查询表单
    //////////////////////////////////////////////////

    const defaultSearchForm = {
      queryLikeStr: '', // 模糊查询关键字
      name: null,  // 名称
      key: null,  // 标识
      category: null,  // 分类
      createTime: null,  // 创建时间
      lastUpdateTime: null,  // 最后更新时间
      version: null,  // 版本
      deploymentId: null,  // 部署ID
      latestVersion: true
    }

    /**
     * 查询表单
     */
    const searchForm = reactive(cloneDeep(defaultSearchForm))

    //////////////////////////////////////////////////
    // 表格
    //////////////////////////////////////////////////

    /**
     * 表格配置
     */
    const tableOptions = reactive<TwTableOptions>({
      id: 'actReModelTable',
      sortConfig: {
        defaultSort: [{ field: 'lastUpdateTime', order: 'desc' }]
      },
      columns: [
        { type: 'checkbox', fixed: 'left', title: '', width: 40 },
        { type: 'seq', fixed: 'left', title: '序号', width: 50 },
        { field: 'name', title: '名称', sortable: true },
        { field: 'key', title: '唯一编码', sortable: true },
        { field: 'categoryName', title: '分类', sortable: true },
        { field: 'createTime', title: '创建时间', sortable: true },
        { field: 'lastUpdateTime', title: '最后更新时间', sortable: true },
        { field: 'version', title: '版本', sortable: true },
        {
          field: 'deploymentId', title: '是否发布', sortable: true, formatter({ cellValue }) {
            if (stringUtils.isNotEmpty(cellValue)) {
              return '已发布'
            }
            return '未发布'
          }
        },
        { title: '操作', fixed: 'right', width: 260, slots: { default: 'action' } }
      ]
    })

    /**
     * 绑定事件
     */
    const tableEvents = reactive({
      cellDblclick(params: { row: ActReModelModel }) {
        if (hasPermission('ACT-RE-MODEL-VIEW')) {
          handleOpenForm('view', params.row)
        } else {
          ElMessage.warning('无权限访问')
        }
      }
    })

    //////////////////////////////////////////////////
    // 函数
    //////////////////////////////////////////////////

    /**
     * 查询表格数据函数
     * @param queryParams
     */
    function searchList(queryParams: ActReModelPageParams) {
      loading.value = true

      apiActReModelSearch(assign(queryParams, searchForm, {
        category: selectTreeNode.code
      }))
        .then((result) => {
          tableData.value = result
        })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 查询表格数据
     */
    function handleSearch() {
      tableRef.value.handleQuery()
    }

    /**
     * 刷新
     */
    function handleRefresh() {
      tableRef.value.handleReload()
    }

    /**
     * 重置
     */
    function handleReset() {
      assign(searchForm, cloneDeep(defaultSearchForm))
      tableRef.value.handleQuery()
    }

    /**
     * 批量删除
     */
    function handleDelete(row?: ActReModelModel) {
      let selectRows: Array<ActReModelModel> = []

      if (row) {
        selectRows = [row]
      } else {
        selectRows = tableRef.value.getSelectRows()
      }

      if (selectRows.length === 0) {
        ElMessage.warning('请选择需要删除的数据')
        return
      }

      ElMessageBox.confirm(`此操作将删除${selectRows.length}条记录, 是否继续?`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          loadingByDel.value = true
          const ids = arraySerializeToStr(selectRows, 'id')
          apiActReModelBatchDeleteByIds(ids)
            .then((result) => {
              if (result?.success) {
                handleRefresh()
                ElMessage.success(result.message)
              } else {
                ElMessage.error(result?.message)
              }
            })
            .catch(() => { })
            .finally(() => {
              loadingByDel.value = false
            })
        })
        .catch(() => {
          ElMessage.info('删除被取消了')
        })
    }

    /**
     * 弹出表单
     */
    function handleOpenForm(action: string, row?: ActReModelModel) {
      formRef.value.handleOpen(action, row, {
        category: selectTreeNode.code
      })
    }


    /**
     * 流程复制
     * @param row 
     */
    function handleCopy(row: ActReModelModel) {
      loading.value = true
      apiActReModelCopy(`${row.id}`).then((result) => {
        if (result?.success) {
          handleRefresh()
          ElMessage.success(result.message)
        } else {
          ElMessage.error(result?.message)
        }
      })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    /**
     * 流程模型设计
     * @param row 
     */
    function handleDesign(row: ActReModelModel) {
      if (row) {
        router.push({
          path: '/flowDesigner',
          query: {
            id: row.id
          }
        })
      } else {
        ElMessage.warning('请选择数据')
      }
    }

    /**
     * 流程部署
     * @param row 
     */
    function handleDeploy(row: ActReModelModel) {
      loading.value = true
      apiActReModelDeploy(`${row.id}`).then((result) => {
        if (result?.success) {
          handleRefresh()
          ElMessage.success(result.message)
        } else {
          ElMessage.error(result?.message)
        }
      })
        .catch(() => { })
        .finally(() => {
          loading.value = false
        })
    }

    //////////////////////////////////////////////////
    // 流程类别树
    //////////////////////////////////////////////////
    const flowCategoryTreeRef = ref()

    /**
     * 选中的树节点
     */
    let selectTreeNode: any = {}

    /**
     * 节点点击事件
     */
    function handleNodeClick(treeNode?: Node) {
      selectTreeNode = treeNode ? treeNode : {}
      handleSearch()
    }

    /**
    * 树刷新
    */
    function handleTreeSearch() { }

    //////////////////////////////////////////////////
    // 生命周期
    //////////////////////////////////////////////////
    onMounted(() => { })


    return {
      loading,
      loadingByDel,
      tableData,
      searchFormRef,
      tableRef,
      formRef,
      state,
      searchForm,
      tableOptions,
      tableEvents,
      isSelectRows,
      searchList,
      handleSearch,
      handleRefresh,
      handleReset,
      handleDelete,
      handleOpenForm,
      flowCategoryTreeRef,
      handleNodeClick,
      handleTreeSearch,
      handleCopy,
      handleDesign,
      handleDeploy
    }
  }
})
